package com.example.controller;


import com.example.common.event.MessageEvent;
import com.example.common.lang.Consts;
import com.example.common.lang.Result;
import com.example.entity.User;
import com.example.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import com.example.controller.BaseController;

import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lv-success
 * @since 2019-04-10
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    UserService userService;

    @Autowired
    ApplicationContext applicationContext;

    @GetMapping("/test")
    public User test() {

        MessageEvent event = new MessageEvent(this, Consts.MESSAGE_EVENT_FAVOR_POST);
        event.setPostId(1L);
        event.setFromUserId(2L);
        event.setToUserId(3L);
        applicationContext.publishEvent(event);

        User user = userService.getById(1L);
        log.info("---------> " + user.toString());
        return user;
    }

    @PostMapping("/add")
    public Result addUser(@Valid User user, BindingResult result) {
        if(result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            for (ObjectError error : allErrors) {
                log.error("here is error ----------> {}", error.getDefaultMessage());
            }
            return Result.failure(allErrors.get(0).getDefaultMessage());
        }

        userService.save(user);

        return Result.success();
    }

}
